import 'package:city_pickers/city_pickers.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:omni_datetime_picker/omni_datetime_picker.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/view/leads/widget/common_date.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

enum LabelType {
  TEXT, //文本
  INPUT, //输入框
  DROW_DOWN, //下拉选择
  LIST, //横着的list选择，一般用于两个item
  DATE, //日期
  DATETIME, //日期加时间
  TEXTAREA, //多文本
  CITY, //省市区
  SELECT, //就是进入其他页面选择
  RATINGBAR, //星际评选
}

class LabelItem extends StatefulWidget {
  final Key? key;
  final String label;
  final String? value;
  final double height;
  final bool isMust;
  final bool isReadOnly;
  final bool isLast;
  final bool isEnabled;
  final LabelType labelType;
  final TextInputType textInputType;
  final bool isPassword;
  final int maxLength;
  final int maxTextLength;
  final int maxLine;
  final bool isModel;
  final bool isSelectMul;
  final double? listItemWidth;
  final double fontSize;
  final Function(dynamic value)? onSelected;
  final Function(String text)? onChanged;
  final Function(String date)? onDateChanged;
  final Function()? onTap;
  final List<Map>? dataList;
  final Map<String, dynamic>? cityData;

//  final int selectedIndex;
  final String? selectedDate;
  final DateTime? minDateTime;
  final DateTime? maxDateTime;

//  final String? locationCode;

  const LabelItem(
      {this.key,
      this.label = "",
      this.value,
      this.height = 45,
      this.isMust = false,
      this.isReadOnly = false,
      this.isLast = false,
      this.isModel = false,
      this.isEnabled = true,
      this.isSelectMul = false,
      this.listItemWidth,
      this.fontSize = 14,
      this.isPassword = false,
      this.labelType = LabelType.TEXT,
      this.maxLength = 20,
      this.maxTextLength = 200,
      this.maxLine = 3,
      this.textInputType = TextInputType.text,
      //this.locationCode,
      this.dataList,
      //this.selectedIndex = 0,
      this.cityData,
      this.selectedDate,
      this.minDateTime,
      this.maxDateTime,
      this.onChanged,
      this.onSelected,
      this.onDateChanged,
      this.onTap})
      : super(key: key);

  @override
  State<LabelItem> createState() => LabelItemState();
}

class LabelItemState extends State<LabelItem> {
  TextEditingController? _textController;
  FocusNode numberFocusNode = new FocusNode();
  dynamic overlayEntry;

  String? label;

  String? value;

  DateTime? selectDate;
  String? currentDate;

  String locationCode = "";
  String? selectLocal;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    numberFocusNode.addListener(() {
      if (numberFocusNode.hasFocus) {
        showOverlay(context);
      } else {
        removeOverlay();
      }
    });

    if (widget.labelType == LabelType.INPUT ||
        widget.labelType == LabelType.TEXTAREA) {
      _textController = TextEditingController.fromValue(
          TextEditingValue(text: widget.value ?? ""));
    } else if (widget.labelType == LabelType.DROW_DOWN ||
        widget.labelType == LabelType.LIST) {
      value = widget.value == null ? "" : widget.value!;
      label = CommonReqUtils.exchangeCodeToName2(widget.dataList!, value);
    } else if (widget.labelType == LabelType.DATE ||
        widget.labelType == LabelType.DATETIME) {
      selectDate = widget.selectedDate == null || widget.selectedDate == ""
          ? DateTime.now()
          : DateUtil.getDateTime(widget.selectedDate!);
      // currentDate = DateUtil.formatDate(selectDate,
      //     format: widget.labelType == LabelType.DATE
      //         ? DateFormats.y_mo_d
      //         : DateFormats.y_mo_d_h_m);
    } else if (widget.labelType == LabelType.CITY) {
      locationCode = widget.value ?? "";
    }
  }

  showOverlay(BuildContext context) {
    if (overlayEntry != null) return;
    OverlayState overlayState = Overlay.of(context);
    overlayEntry = OverlayEntry(builder: (context) {
      return Positioned(
          bottom: MediaQuery.of(context).viewInsets.bottom,
          right: 0.0,
          left: 0.0,
          child: InputDoneView());
    });

    overlayState.insert(overlayEntry);
  }

  removeOverlay() {
    if (overlayEntry != null) {
      overlayEntry.remove();
      overlayEntry = null;
    }
  }

  // void getCityList() {
  //   HttpUtils().get(Api.getRegionList2).then((value) {
  //     if (value.resultCode == 200) {
  //       cityData = value.data;
  //       setState(() {});
  //     }
  //   });
  // }

  void refreshCity(val, String areaStr) {
    locationCode = val;
    selectLocal = areaStr;
    print("=================xxx=============$areaStr");
    setState(() {});
  }

  ///刷新type为 INPUT和TEXTAREA的初始值
  void refreshInput(String val) {
    setState(() {
      _textController =
          TextEditingController.fromValue(TextEditingValue(text: val ?? ""));
    });
  }

  ///刷新type为列表没有存入缓存的DROW_DOWN或者LIST页面的初始值
  void refreshList(list, val) {
    setState(() {
      value = val.toString();
      label = CommonReqUtils.exchangeCodeToName2(list, val);
    });
  }

  ///刷新type为 日期的初始值
  void refreshDate(date) {
    if (date is DateTime) {
      selectDate = date;
      currentDate = DateUtil.formatDate(selectDate,
          format: widget.labelType == LabelType.DATE
              ? DateFormats.y_mo_d
              : DateFormats.y_mo_d_h_m);
    } else if (date is String) {
      selectDate = DateUtil.getDateTime(date);
      currentDate = date;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return widget.labelType == LabelType.TEXTAREA
        ? _getTextAreaWidget()
        : Container(
            height: widget.height.px,
            padding: EdgeInsets.symmetric(horizontal: 15.px),
            decoration: BoxDecoration(
                color: Colors.white,
                border: widget.isLast
                    ? const Border()
                    : Border(
                        bottom: BorderSide(
                          color: WColors.border, // 边框颜色
                          width: 0.5.px, // 边框宽度
                        ),
                      )),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Offstage(
                      offstage: !widget.isMust,
                      child: WText(
                        "*",
                        style: TextStyle(
                            color: WColors.redMain,
                            fontSize: WDimens.tsXXLarge),
                      ),
                    ),
                    WText(
                      widget.label,
                      style: TextStyle(
                          color: WColors.mainTextColor,
                          fontSize: widget.fontSize.px),
                    )
                  ],
                ),
                _getTypeWidget(),
              ],
            ),
          );
  }

  Widget _getTextAreaWidget() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
        //constraints: BoxConstraints(maxHeight: 100.px),
        decoration: BoxDecoration(
            color: Colors.white,
            border: widget.isLast
                ? const Border()
                : Border(
                    bottom: BorderSide(
                      color: WColors.border, // 边框颜色
                      width: 0.5.px, // 边框宽度
                    ),
                  )),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Offstage(
                  offstage: !widget.isMust,
                  child: WText(
                    "*",
                    style: TextStyle(
                        color: WColors.redMain, fontSize: WDimens.tsXXLarge),
                  ),
                ),
                WText(
                  widget.label,
                  style: TextStyle(
                      color: WColors.mainTextColor,
                      fontSize: widget.fontSize.px),
                )
              ],
            ),
            widget.isEnabled
                ? TextField(
                    keyboardAppearance: Brightness.light,
                    autofocus: false,
                    maxLength: widget.maxTextLength,
                    controller: _textController,
                    textAlign: TextAlign.start,
                    scrollPadding: EdgeInsets.zero,
                    onChanged: (s) {
                      if (widget.onChanged != null) {
                        widget.onChanged!(s);
                      }
                    },
                    maxLines: widget.maxLine,
                    keyboardType: widget.textInputType,
                    style: TextStyle(
                      color: WColors.subTextColor,
                      fontSize: WDimens.tsMedium,
                    ),
                    decoration: InputDecoration(
                      isCollapsed: true,
                      counterStyle: TextStyle(
                          color: WColors.hintTextColor,
                          fontSize: WDimens.tsSmall),
                      focusedBorder: const OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      disabledBorder: const OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      enabledBorder: const OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      border: OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 1.px, color: WColors.border)),
                      hintText: "请输入",
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 5.px, vertical: 0),
                      hintStyle: TextStyle(
                          color: WColors.CCCCCCC, fontSize: widget.fontSize.px),
                    ),
                  )
                : Padding(
                    padding: EdgeInsets.all(5.px),
                    child: WText(widget.value ?? "",
                        style: TextStyle(
                            color: WColors.subTextColor,
                            fontSize: widget.fontSize.px)),
                  )
          ],
        ));
  }

  Widget _getTypeWidget() {
    if (widget.labelType == LabelType.INPUT) {
      return _inputWidget();
    } else if (widget.labelType == LabelType.DROW_DOWN) {
      return _spinnerWidget();
    } else if (widget.labelType == LabelType.LIST) {
      return _listWidget();
    } else if (widget.labelType == LabelType.TEXT) {
      return Expanded(
          child: WText(
        widget.value ?? "",
        textAlign: TextAlign.end,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
            color:
                widget.isEnabled ? WColors.subTextColor : WColors.hintTextColor,
            fontSize: widget.fontSize.px),
      ));
    } else if (widget.labelType == LabelType.DATE ||
        widget.labelType == LabelType.DATETIME) {
      return _dateWidget();
    } else if (widget.labelType == LabelType.CITY) {
      return _cityWidget();
    } else if (widget.labelType == LabelType.SELECT) {
      return _goOtherWidget();
    }else if(widget.labelType == LabelType.RATINGBAR){
      return RatingBar(
            initialRating: double.parse(StringUtils.safeGetValue(widget.value, placeHolder: "0.0")),
            direction: Axis.horizontal,
            allowHalfRating: false,
            itemCount: 5,
            itemSize: 30,
            ratingWidget: RatingWidget(
              full: const Icon(Icons.star_rate,color: WColors.orange,),
              half: const Icon(Icons.star_rate,color: WColors.green,),
              empty: const Icon(Icons.star_rate,color: WColors.CCCCCCC,),
            ),
            ignoreGestures: widget.isReadOnly,
            itemPadding: EdgeInsets.symmetric(horizontal: 6.0),
            onRatingUpdate: (rating) {
              unFocus(context);
              if (widget.onSelected != null) {
                widget.onSelected!(StringUtils.safeGetValue(rating));
                setState(() {});
              }
            },
          );
    }

    return Container();
  }

  Widget _inputWidget() {
    return Expanded(
        child: TextField(
      keyboardAppearance: Brightness.light,
      autofocus: false,
      focusNode:
          widget.textInputType == TextInputType.number ? numberFocusNode : null,
      maxLength: widget.maxLength,
      controller: _textController,
      textAlign: TextAlign.end,
      obscureText: widget.isPassword,

      ///   maxLines: 1,
      onChanged: (s) {
        if (widget.onChanged != null) {
          widget.onChanged!(s);
        }
      },
      keyboardType: widget.textInputType,
      style:
          TextStyle(color: WColors.subTextColor, fontSize: widget.fontSize.px),
      decoration: InputDecoration(
        counterText: "",
        isCollapsed: true,
        focusedBorder: const OutlineInputBorder(
            borderSide: BorderSide(width: 0, color: Colors.transparent)),
        disabledBorder: const OutlineInputBorder(
            borderSide: BorderSide(width: 0, color: Colors.transparent)),
        enabledBorder: const OutlineInputBorder(
            borderSide: BorderSide(width: 0, color: Colors.transparent)),
        border: const OutlineInputBorder(
            borderSide: BorderSide(width: 0, color: Colors.transparent)),
        hintText: "请输入",
        hintStyle:
            TextStyle(color: WColors.CCCCCCC, fontSize: widget.fontSize.px),
      ),
    ));
  }

  //
  Widget _goOtherWidget() {
    return GestureDetector(
      onTap: () {
        unFocus(context);
        print("=======================点击1");
        if (widget.onTap != null) {
          print("=======================点击2");
          widget.onTap!();
        }
      },
      child: Container(
        color: WColors.white,
        height: widget.height,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(
              StringUtils.isEmpty2(widget.value) ? "请选择" : widget.value!,
              style: TextStyle(
                color: StringUtils.isEmpty2(widget.value) ||
                        (widget.value != null && widget.value!.contains("签署"))
                    ? WColors.CCCCCCC
                    : WColors.subTextColor,
                fontSize: widget.fontSize.px,
              ),
            ),
            SizedBox(width: 5.px),
            Image.asset(
              "images/ic_right.png",
              color: WColors.CCCCCCC,
              width: 12.px,
              height: 12.px,
            )
          ],
        ),
      ),
    );
  }

  unFocus(BuildContext mContext) {
    final otherNode = FocusNode();
    FocusScope.of(mContext).requestFocus(otherNode);
    otherNode.unfocus();
  }

  Widget _listWidget() {
    List<Widget> list = [];
    for (int i = 0; i < widget.dataList!.length; i++) {
      String itemVal = widget.dataList![i]["value"];
      list.add(StatusBtn(
        text: widget.dataList![i]["label"],
        isItemBtn: true,
        width: widget.listItemWidth == null
            ? (widget.isModel ? 40.px : 60.px)
            : widget.listItemWidth!,
        height: 30.px,
        color: value == itemVal ? WColors.primaryColor : WColors.border,
        isTag: value == itemVal,
        fontColor:
            value == itemVal ? WColors.primaryColor : WColors.mainTextColor,
        margin: EdgeInsets.only(left: 10.px),
        onPressed: () {
          unFocus(context);
          if (widget.onSelected != null) {
            value == itemVal ? value = null : value = itemVal;
            widget.onSelected!(value);
            setState(() {});
          }
        },
      ));
    }
    return Row(
      children: list,
    );
  }

  Widget _spinnerWidget() {
    return GestureDetector(
        onTap: () {
          unFocus(context);
          if (widget.onSelected != null) {
            WPopupWindow.showSpinner(
                dataList: widget.dataList!,
                context: context,
                value: value,
                onSelected: (itemVal, itemLabel) {
                  label = itemLabel;
                  value = itemVal;
                  widget.onSelected!(itemVal);
                  setState(() {});
                });
          }
        },
        child: SizedBox(
          height: 48.px,
          // width: SizeUtils.screenW() - 140.px,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text(
                StringUtils.isEmpty2(label)
                    ? (widget.isEnabled ? "请选择" : "")
                    : label!,
                style: TextStyle(
                  color: widget.isEnabled
                      ? StringUtils.isEmpty2(label)
                          ? WColors.CCCCCCC
                          : WColors.subTextColor
                      : WColors.hintTextColor,
                  fontSize: widget.fontSize.px,
                ),
              ),
              Offstage(
                offstage: !widget.isEnabled,
                child: Padding(
                  padding: EdgeInsets.only(left: 5.px),
                  child: Image.asset(
                    "images/ic_right.png",
                    color: WColors.CCCCCCC,
                    width: 12.px,
                  ),
                ),
              ),
            ],
          ),
        ));
  }

  Widget _dateWidget() {
    return GestureDetector(
      onTap: () {
        unFocus(context);
        _showDatePickerForDate();
      },
      child: SizedBox(
        height: 48.px,
        //    width: SizeUtils.screenW() - 140.px,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            WText(
              StringUtils.isEmpty(currentDate)
                  ? (widget.isEnabled ? "请选择" : "")
                  : currentDate!,
              style: TextStyle(
                color: widget.isEnabled
                    ? StringUtils.isEmpty(currentDate)
                        ? WColors.CCCCCCC
                        : WColors.subTextColor
                    : WColors.hintTextColor,
                fontSize: widget.fontSize.px,
              ),
            ),
            Offstage(
              offstage: !widget.isEnabled,
              child: Padding(
                padding: EdgeInsets.only(left: 5.px),
                child: Image.asset(
                  "images/ic_right.png",
                  color: WColors.CCCCCCC,
                  width: 12.px,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _showDatePickerForDate() {
    if (widget.labelType == LabelType.DATE) {
      CommonDate.showPicker(
          context: context,
          firstDate: widget.minDateTime ?? DateTime(2020, 1, 1),
          lastDate: widget.maxDateTime ?? DateTime(2030, 12, 31),
          currentDate: selectDate,
          value: [selectDate ?? DateTime.now()]).then((dateTime) {
        print("=====================");
        print(dateTime);
        if (dateTime != null && dateTime.isNotEmpty) {
          selectDate = dateTime[0];
          currentDate =
              DateUtil.formatDate(selectDate, format: DateFormats.y_mo_d);
          if (widget.onDateChanged != null) {
            widget.onDateChanged!(currentDate!);
          }
        }
      });
    } else {
      return showOmniDateTimePicker(
              context: context,
              initialDate: selectDate,
              firstDate: widget.minDateTime ?? DateTime(2020, 1, 1),
              lastDate: widget.maxDateTime ?? DateTime(2030, 12, 31),
              is24HourMode: true,
              theme: ThemeData(
                  colorScheme:
                      ColorScheme.fromSeed(seedColor: WColors.primaryColor)))
          .then((dateTime) {
        if (dateTime != null) {
          selectDate = dateTime;
          currentDate =
              DateUtil.formatDate(selectDate, format: DateFormats.y_mo_d_h_m);
          if (widget.onDateChanged != null) {
            widget.onDateChanged!(currentDate!);
          }
          setState(() {});
        }
      });
      // return DatePicker.showDatePicker(context,
      //     pickerMode: DateTimePickerMode.time,
      //     minDateTime: widget.minDateTime ?? DateTime(2020, 1, 1),
      //     maxDateTime: widget.maxDateTime ?? DateTime(2030, 12, 31),
      //     initialDateTime: selectDate,
      //     locale: DateTimePickerLocale.zh_cn,
      //     dateFormat: "yyyy|MM|dd HH:mm",
      //     onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      //   print("选择 $dateTime");
      //   selectDate = dateTime;
      //   currentDate =
      //       DateUtil.formatDate(selectDate, format: DateFormats.y_mo_d_h_m);
      //   if (widget.onDateChanged != null) {
      //     widget.onDateChanged!(currentDate!);
      //   }
      //   setState(() {});
      // });
    }
  }

  Widget _cityWidget() {
    return GestureDetector(
        onTap: () {
          unFocus(context);
          _showCityPicker().then((res) {
            if (res == null) {
              return;
            }
            print(res);
            locationCode = res.areaId;
            selectLocal = "${res.provinceName}${res.cityName}${res.areaName}";
            if (widget.onSelected != null) {
              widget.onSelected!(res);
            }
            setState(() {});
          });
        },
        child: SizedBox(
          height: 48.px,
          width: SizeUtils.screenW() - 140.px,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text(
                StringUtils.isEmpty(selectLocal)
                    ? (widget.isEnabled ? "请选择" : "")
                    : selectLocal!,
                style: TextStyle(
                  color: widget.isEnabled
                      ? StringUtils.isEmpty(selectLocal)
                          ? WColors.CCCCCCC
                          : WColors.subTextColor
                      : WColors.hintTextColor,
                  fontSize: widget.fontSize.px,
                ),
              ),
              SizedBox(
                width: 5.px,
              ),
              Image.asset(
                "images/ic_right.png",
                color: WColors.CCCCCCC,
                width: 12.px,
              ),
            ],
          ),
        ));
  }

  Future _showCityPicker() async {
    return CityPickers.showCityPicker(
        height: 250.px,
        context: context,
        locationCode: locationCode,
        citiesData: Map<String, dynamic>.from(widget.cityData!["citiesData"]),
        provincesData:
            Map<String, String>.from(widget.cityData!["provincesData"]),
        cancelWidget: WText(
          "取消",
          style:
              TextStyle(fontSize: WDimens.tsLarge, color: WColors.subTextColor),
        ),
        confirmWidget: WText(
          "确定",
          style:
              TextStyle(fontSize: WDimens.tsLarge, color: WColors.primaryColor),
        ));
  }
}

class InputDoneView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: Align(
        alignment: Alignment.topRight,
        child: Padding(
          padding: const EdgeInsets.only(top: 4.0, bottom: 4.0),
          child: CupertinoButton(
            padding: const EdgeInsets.only(right: 24.0, top: 8.0, bottom: 8.0),
            onPressed: () {
              FocusScope.of(context).requestFocus(new FocusNode());
            },
            child: const Text("完成",
                style: TextStyle(
                    color: Colors.blueAccent, fontWeight: FontWeight.bold)),
          ),
        ),
      ),
    );
  }
}
